package com.txr.news.controlleradvice;

import com.txr.news.customexception.BusinessException;
import com.txr.news.customexception.SystemException;
import com.txr.news.pojo.Code;
import com.txr.news.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * SpringMVC的亮点
 * 项目异常处理器：把异常分为业务异常、系统异常、其他异常分别进行处理
 */
@RestControllerAdvice
public class ProjectExceptionAdvice {

    //业务异常处理
    @ExceptionHandler(BusinessException.class)
    public Result dealBusinessException(BusinessException throwable){
        System.out.println(throwable.getMessage());
        System.out.println(throwable);
        System.out.println("异常被捕获了");
        Result result = new Result(300,throwable.getMessage(),null,Code.Exception);
        return result;
    }

    //系统异常处理
    @ExceptionHandler(SystemException.class)
    public Result dealSystemException(SystemException throwable){
        System.out.println(throwable.getMessage());
        System.out.println(throwable);
        System.out.println("异常被捕获了");
        throwable.getCause().printStackTrace();
        Result result = new Result(500,"系统繁忙！",null,Code.Exception);
        return result;
    }

    //其他异常处理
    @ExceptionHandler(Exception.class)
    public Result dealException(Throwable throwable){
        System.out.println(throwable.getMessage());
        System.out.println(throwable);
        System.out.println("异常被捕获了");
        Result result=new Result(500,"异常发生"+ throwable.getMessage(),null, Code.Exception);
        return result;
    }
}
